# -*- coding: utf-8 -*-
"""
_______________________________________
    File Name:   
    Description:
    Author:     Ethan
    date:       2024/7/12
_______________________________________
"""  # -*- coding: utf-8 -*-


from PyQt5.QtSql import QSqlDatabase

# # 创建数据库连接
# db = QSqlDatabase.addDatabase('QSQLITE')
# db.setDatabaseName(':memory:')
#
# # 打开数据库
# if not db.open():
#     print("无法打开数据库")
# else:
#     print("数据库打开成功")

from PyQt5.QtSql import QSqlDatabase

# 创建数据库连接
db = QSqlDatabase.addDatabase('QMYSQL')
db.setHostName('localhost')  # 或者是数据库服务器的IP地址
db.setDatabaseName('mysql')
db.setUserName('root')
db.setPassword('admin123')
db.setPort(3306)  # MySQL默认端口

# 打开数据库连接
if not db.open():
    print("无法连接数据库")
else:
    print("数据库连接成功")

# 使用数据库...

# 关闭数据库连接
db.close()

# 连接到 MySQL 数据库
import pymysql
connection = pymysql.connect(

host='localhost', # 数据库主机地址
user='root', # 数据库用户名
password='admin123', # 数据库密码
database='mysql' # 数据库名

)

try:

    with connection.cursor() as cursor:
        # 创建一个新表
        sql = "CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT)"
        cursor.execute(sql)
        # 插入数据
        sql = "INSERT INTO users (name, age) VALUES (%s, %s)"
        cursor.execute(sql, ('John', 22))
         # 提交事务
        connection.commit()
        # 执行查询
        sql = "SELECT * FROM users"
        cursor.execute(sql)
        # 获取查询结果
        result = cursor.fetchall()
        for row in result:
            print(row)
finally:
    # 关闭数据库连接
    connection.close()